# encoding:utf-8
import urllib


class Signature(object):
    def __init__(self, secret_key, **kwargs):
        self.secret_key = secret_key.encode('utf-8') if isinstance(secret_key, unicode) else secret_key
        self.params = kwargs

    @property
    def url_prams(self):
        self.check_prams()
        keys = self.params.items()
        keys.sort(key=lambda key: key[0])
        keys = [(key[0].encode('utf-8'), key[1].encode('utf-8')) for key in keys]
        return urllib.urlencode(keys)

    def signature(self, url_prams):
        from Crypto.Hash import SHA, HMAC
        from base64 import b64encode
        hmac = HMAC.new(self.secret_key, url_prams, SHA)
        return b64encode(hmac.hexdigest())

    def get_url(self):
        url = u''
        for key in self.params.keys():
            url = u''.join((url, key, '=', self.params.get(key)))
        url = u''.join((url, '&timestamp', '=', self.timestamp,))
        return u''.join((url, '&signature', '=', self.signature(url)))

    @property
    def timestamp(self):
        import datetime
        return datetime.datetime.now().strftime('%Y%m%d%H%M%S')

    def check_signature(self, signature):
        check_signature = self.signature(self.url_prams)
        if signature == check_signature:
            return True
        else:
            return False

    def check_prams(self):
        keys = self.params.keys()
        if 'signature' in keys:
            self.params.pop('signature')
